/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package project1;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
 *
 * @author haihip
 */
public class LoginView extends javax.swing.JFrame {

    /**
     * Creates new form LoginView
     */
    public LoginView() {
        initComponents();
        this.getRootPane().setDefaultButton(btn_login);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        input_user = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        btn_login = new javax.swing.JButton();
        btn_exit = new javax.swing.JButton();
        input_pass = new javax.swing.JPasswordField();
        txt_error = new javax.swing.JLabel();
        status = new javax.swing.JLabel();
        downloadPercent = new javax.swing.JProgressBar();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Đăng nhập");
        setAlwaysOnTop(true);
        setMinimumSize(new java.awt.Dimension(438, 240));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));
        jPanel1.setMaximumSize(new java.awt.Dimension(438, 240));
        jPanel1.setMinimumSize(new java.awt.Dimension(438, 240));
        jPanel1.setPreferredSize(new java.awt.Dimension(438, 240));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("Đăng Nhập Hệ Thống");

        jLabel2.setText("Mã Số SV/GV:");

        input_user.setText("20118518");

        jLabel3.setText("Mật Khẩu     :");

        btn_login.setText("Đăng Nhập");
        btn_login.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_loginActionPerformed(evt);
            }
        });

        btn_exit.setText("Thoát");
        btn_exit.setPreferredSize(new java.awt.Dimension(87, 23));
        btn_exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_exitActionPerformed(evt);
            }
        });

        input_pass.setText("123");

        txt_error.setForeground(new java.awt.Color(255, 0, 0));
        txt_error.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        txt_error.setMaximumSize(new java.awt.Dimension(1000, 14));
        txt_error.setMinimumSize(new java.awt.Dimension(0, 14));
        txt_error.setPreferredSize(new java.awt.Dimension(0, 14));

        status.setText("Đang kiểm tra phiên bản...");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(62, 62, 62)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(input_user, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(btn_login)
                                        .addGap(18, 18, 18)
                                        .addComponent(btn_exit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(input_pass, javax.swing.GroupLayout.PREFERRED_SIZE, 242, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(jLabel1)))
                .addContainerGap(66, Short.MAX_VALUE))
            .addComponent(txt_error, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(downloadPercent, javax.swing.GroupLayout.PREFERRED_SIZE, 207, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(status, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(12, 12, 12)
                .addComponent(txt_error, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(input_user, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(input_pass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btn_login)
                    .addComponent(btn_exit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 27, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(status, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(downloadPercent, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    SqlFunc sql = new SqlFunc();
    private void btn_exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_exitActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_btn_exitActionPerformed
    String[] CheckLogin(String user,String pass)
    {
        String[] ret = new String[20];
        int num = sql.numrows("select password from user,giangvien where `giangvien`.`msgv`='"+user+"' and `giangvien`.`ID_User` = `user`.`ID_User`");
        if(num==1)
        {
            try {
                ResultSet rs = sql.select("select `user`.`ID_User` as ID_User,ten,ngaysinh,gioitinh,quequan,dienthoai,email,password,loai,MSGV,TenBoMon from user,giangvien,BoMon where `giangvien`.`msgv`='"+user+"' and `giangvien`.`ID_User` = `user`.`ID_User` and `giangvien`.`ID_BoMon`=`BoMon`.`ID_BoMon`");
                if(rs.next() && rs.getString("password").equals(pass))
                {
                    for(int i =1;i <= 11;i++)
                    {
                        ret[i] = rs.getString(i);
                        System.out.println(i+"/"+ret[i]);
                    }
                }
            } catch (SQLException ex) {
                Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        else
        {
            num = sql.numrows("select password from user,sinhvien where `sinhvien`.`mssv`='"+user+"' and `sinhvien`.`ID_User` = `user`.`ID_User`");
            if(num==1)
            {
                try {
                ResultSet rs = sql.select("select `user`.`ID_User` as ID_User,ten,ngaysinh,gioitinh,quequan,dienthoai,email,password,loai,mssv,nganhHoc,khoaHoc from user,sinhvien where `sinhvien`.`mssv`='"+user+"' and `sinhvien`.`ID_User` = `user`.`ID_User`");
                if(rs.next() && rs.getString("password").equals(pass))
                {
                    for(int i =1;i <= 12;i++)
                    {
                        ret[i] = rs.getString(i);
                        System.out.println(i+"/"+ret[i]);
                    }
                }
            } catch (SQLException ex) {
                Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
            }
            }
            else
            {
                num = sql.numrows("select password from user,canbo where `canbo`.`mscb`='"+user+"' and `canbo`.`ID_User` = `user`.`ID_User`");
                if(num==1)
                {
                    try {
                    ResultSet rs = sql.select("select `user`.`ID_User` as ID_User,ten,ngaysinh,gioitinh,quequan,dienthoai,email,password,loai,mscb from user,canbo where `canbo`.`mscb`='"+user+"' and `canbo`.`ID_User` = `user`.`ID_User`");
                    if(rs.next() && rs.getString("password").equals(pass))
                    {
                        for(int i =1;i <= 10;i++)
                        {
                            ret[i] = rs.getString(i);
                            System.out.println(i+"/"+ret[i]);
                        }
                    }
                    } catch (SQLException ex) {
                    Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }
        return ret;
        
    }
    private void btn_loginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_loginActionPerformed
        // TODO add your handling code here:
        String user = input_user.getText();
        String pass = input_pass.getText();
        if(!user.equals("") && !pass.equals(""))
        {
            String[] ret = CheckLogin(user, pass);
            if(ret[1]!=null)
            {
                this.setVisible(false);
                this.setAlwaysOnTop(false);
                project1.Project1.User=ret;
                Frame sys = new Frame();
            }
            else
            {
                txt_error.setText("Sai thông tin tài khoản!");
            }
        }
        else
        {
            txt_error.setText("Vui lòng điền đầy đủ thông tin!");
        }
        
    }//GEN-LAST:event_btn_loginActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        status.setText("Đang kiểm tra phiên bản...");
        try {
            URL url = new URL(Project1.UrlServer);
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            String str;
            str = in.readLine();
            if(str!=null)
            {
                if(Project1.version.equals(str))
                {
                    status.setText("Phiên bản mới nhất: "+Project1.version);
                }
                else
                {
                    status.setText("Chuẩn bị nâng cấp phiên bản...");
                    Thread t = new Thread(){
                        public void run(){
                       //     CheckUpdate();
                        }
                    };
                    t.start();
                }
            }
            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        }
       
    }//GEN-LAST:event_formWindowOpened

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Windows".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginView.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginView().setVisible(true);
            
            }
        });
    }
    public void CheckUpdate()
    {
        download(Project1.UrlDownload, Project1.NameProgram);
        try {
            restartApplication();
        } catch (IOException ex) {
            Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
        } catch (URISyntaxException ex) {
            Logger.getLogger(LoginView.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
public void restartApplication() throws IOException, URISyntaxException
{
  final String javaBin = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
  final File currentJar = new File(Project1.class.getProtectionDomain().getCodeSource().getLocation().toURI());

  /* is it a jar file? */
  if(!currentJar.getName().endsWith(".jar"))
    return;

  /* Build command: java -jar application.jar */
  final ArrayList<String> command = new ArrayList<String>();
  command.add(javaBin);
  command.add("-jar");
  command.add(currentJar.getPath());

  final ProcessBuilder builder = new ProcessBuilder(command);
  builder.start();
  System.exit(0);
}
public void download(String remotePath, String localPath) {
    BufferedInputStream in = null;
    FileOutputStream out = null;

    try {
        URL url = new URL(remotePath);
        URLConnection conn = url.openConnection();
        int size = conn.getContentLength();

        if (size < 0) {
            System.out.println("Could not get the file size");
        } else {
            System.out.println("File size: " + size);
        }

        in = new BufferedInputStream(url.openStream());
        out = new FileOutputStream(localPath);
        byte data[] = new byte[1024];
        int count;
        double sumCount = 0.0;
        downloadPercent.setValue(0);
        while ((count = in.read(data, 0, 1024)) != -1) {
            out.write(data, 0, count);

            sumCount += count;
            if (size > 0) {
                downloadPercent.setValue((int) (sumCount / size * 100.0));
            }
        }
        downloadPercent.setValue(100);

    } catch (MalformedURLException e1) {
    } catch (IOException e2) {
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e3) {
            }
        if (out != null)
            try {
                out.close();
            } catch (IOException e4) {
            }
    }
}
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_exit;
    private javax.swing.JButton btn_login;
    private javax.swing.JProgressBar downloadPercent;
    private javax.swing.JPasswordField input_pass;
    private javax.swing.JTextField input_user;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel status;
    private javax.swing.JLabel txt_error;
    // End of variables declaration//GEN-END:variables
}
